defmodule ProgContestWeb.ContestController do
  use ProgContestWeb, :controller

  alias ProgContest.Contests

  def index(conn, _params) do
    json(conn, Contests.list_contests())
  end

  def create(conn, %{"contest" => contest_params}) do
    case Contests.create_contest(contest_params) do
      {:ok, contest} ->
        conn
        |> put_status(201)
        |> json(contest)
      {:error, changeset} ->
        errors(conn, changeset)
    end
  end

  def update(conn, %{"id" => id, "contest" => contest_params}) do
    case id |> Contests.get_contest!() |> Contests.update_contest(contest_params) do
      {:ok, contest} -> json(conn, contest)
      {:error, changeset} -> errors(conn, changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    case id |> Contests.get_contest!() |> Contests.delete_contest() do
      {:ok, _} -> send_resp(conn, 204, "")
      {:error, changeset} -> errors(conn, changeset)
    end
  end
end
